<template>
  <ElDrawer v-model="opened" title="标识物种" size="40%" destroy-on-close>
    <ElSkeleton v-if="loading" animated :rows="10" />
    <ElForm v-else :model="form" :rules="rules" ref="formRef" status-icon>
      <ElFormItem label="物种" :label-width="labelWidth" prop="speciesCode">
        <ElSelect v-model="form.speciesCode" :clearable="true">
          <ElOption v-for="item in speciesTypeDictList" :key="item.value" :value="item.value" :label="item.label"></ElOption>
        </ElSelect>
      </ElFormItem>
    </ElForm>
    <div v-if="form.fileType === 'IMAGE'"><el-image :src="form.filePath" /></div>
    <div v-if="form.fileType === 'VIDEO'">
      <video ref="videoPlayer" controls :src="form.filePath" style="height: 500px; width: 100%"></video>
    </div>
    <template #footer>
      <ElButton type="primary" @click="onSaveClicked">保存</ElButton>
      <ElButton @click="onCancelClicked">取消</ElButton>
    </template>
  </ElDrawer>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted } from 'vue'
import { ElForm, ElFormItem, FormRules, FormInstance, ElMessage } from 'element-plus'
import { WildCameraAttach, updateSpeciesCode, getWildCameraAttachDetail } from '@api/tby/education/wildCameraAttach'
import { listDictByType } from '@api/uc/dict/index'

const labelWidth = 100
const opened = ref(false)
const loading = ref(true)
const formRef = ref<FormInstance>()
const form = ref<Partial<WildCameraAttach.Record>>({})
const speciesTypeDictList = ref<OptionType[]>([])

onMounted(async () => {
  let { data } = await listDictByType('species_type')
  speciesTypeDictList.value = data
})

const rules = reactive<FormRules>({
  speciesCode: [{ required: true, message: '请选择物种', trigger: 'blur' }]
})

const open = async (id: number) => {
  form.value = {}
  opened.value = true
  try {
    const { data } = await getWildCameraAttachDetail(id!)
    loading.value = false
    form.value = data
  } finally {
    loading.value = false
  }
  formRef.value?.clearValidate()
}

function close() {
  loading.value = true
  opened.value = false
}

const onSaveClicked = () => {
  if (!formRef.value) return
  formRef.value?.validate(valid => {
    if (!valid) {
      return
    }
    let data = speciesTypeDictList.value.find(item => item.value === form.value.speciesCode)
    if (!data) {
      ElMessage.error('物种错误')
      return
    }
    form.value.speciesName = data.label
    updateSpeciesCode(form.value.id!, form.value.speciesCode!, form.value.speciesName!).then(() => {
      sendSuccess()
      close()
    })
  })
}

const onCancelClicked = () => {
  close()
}

defineExpose({
  open,
  close
})

const emit = defineEmits(['success'])

function sendSuccess() {
  emit('success')
}
</script>
